package com.example.examsystem.controller;

import com.example.examsystem.service.CaptchaService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/captcha")
@RequiredArgsConstructor
public class CaptchaController {

    private final CaptchaService captchaService;

    /**
     * 获取图片验证码
     */
    @GetMapping("/image")
    public ResponseEntity<?> getImageCaptcha() {
        try {
            log.info("Generating image captcha...");
            Map<String, Object> captchaMap = captchaService.generateImageCaptcha();
            String captchaKey = (String) captchaMap.get("key");
            byte[] captchaImage = (byte[]) captchaMap.get("image");

            String base64Image = Base64.getEncoder().encodeToString(captchaImage);
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("key", captchaKey);
            response.put("image", base64Image);
            
            log.info("Image captcha generated successfully with key: {}", captchaKey);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("Generate captcha error: ", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                .body(Map.of("success", false, "message", "生成验证码失败"));
        }
    }

    /**
     * 发送短信验证码
     */
    @PostMapping("/sms")
    public ResponseEntity<?> sendSmsCode(@RequestBody Map<String, String> request) {
        try {
            String phone = request.get("phone");
            if (phone == null || phone.trim().isEmpty()) {
                return ResponseEntity.badRequest()
                    .body(Map.of("success", false, "message", "手机号不能为空"));
            }
            
            String captchaKey = captchaService.generateSmsCaptcha(phone);
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("key", captchaKey);
            response.put("message", "验证码已发送");
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("Send SMS captcha error: ", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                .body(Map.of("success", false, "message", "发送验证码失败"));
        }
    }
}




